import { Request, Response } from "express";
import UserModel from "../../schema/user";
import { getToken } from "../../utils/jwt";

import { Common, ResStatus } from "../common/common";
const CommonIns = new Common(UserModel);
const ResStatusIns = new ResStatus();

class System {
  constructor() {}

  async login(req: Request, res: Response) {
    try {
      const { account, password } = req.body;

      const users = await CommonIns.Find({ account, password });

      if (!users.length) {
        ResStatusIns.isNotExist(res);
      } else {
        const user = users[0];

        // 加密对象
        const payload = {
          id: user.id,
          account: user.account,
          password: user.password,
          name: user.name,
          roleId: user.roleId,
          gender: user.gender,
          avatar: user.avatar,
          desc: user.desc,
          createdTime: user.createdTime,
          updatedTime: user.updatedTime,
          creator: user.creator,
        };

        // 获取 token
        const token = await getToken(payload);

        // 将 token 设置为 cookie
        res.cookie("token", token, {
          // httpOnly: true,
          maxAge: 1000 * 60 * 60 * 24, // 1 天过期
        });

        ResStatusIns.Success(res, { ...payload, token });
      }
    } catch (err) {
      ResStatusIns.Database(res, err);
    }
  }
}

export default System;
